#include <head.h>

#define MAX 10

char product[MAX]; // 产品
int product_len;   // 产品数量

pthread_mutex_t mutex;

void *func_producer(void *val);
void *func_consumer_1(void *val);
void *func_consumer_2(void *val);

int main(int argc, char const *argv[])
{
    pthread_t Tid[3];
    pthread_mutex_init(&mutex, NULL);
    product_len = -1;

    pthread_create(&Tid[0], NULL, func_producer, NULL);
    pthread_create(&Tid[1], NULL, func_consumer_1, NULL);
    pthread_create(&Tid[2], NULL, func_consumer_2, NULL);

    for (size_t i = 0; i < 3; i++)
    {
        pthread_join(Tid[i], NULL);
    }
    pthread_mutex_destroy(&mutex);

    return 0;
}

void *func_producer(void *val)
{
    char buf[128] = "student@student-machine:~/HQYJ/work8-27$";
    int buf_i = 0;
    while (1)
    {
        if (product_len < MAX)
        {
            pthread_mutex_lock(&mutex);
            product[product_len] = buf[buf_i];
            buf_i++;
            product[product_len + 1] = '\0';
            product_len++;
            printf("生产完成 产品数量 %d 产品 %c\n", product_len + 1, product[product_len - 1]);
            pthread_mutex_unlock(&mutex);
            sleep(1);
        }
    }
}

void *func_consumer_1(void *val)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        if (product_len <= -1)
        {
            pthread_mutex_unlock(&mutex);
            sleep(1);
            continue;
        }
        product_len--;
        printf("消费完成 产品数量 %d 产品 %c\n", product_len + 1, product[product_len]);

        pthread_mutex_unlock(&mutex);
        sleep(6);
    }
}

void *func_consumer_2(void *val)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        if (product_len <= -1)
        {
            pthread_mutex_unlock(&mutex);
            sleep(1);
            continue;
        }
        product_len--;
        printf("消费完成 产品数量 %d 产品 %c\n", product_len + 1, product[product_len]);

        pthread_mutex_unlock(&mutex);
        sleep(6);
    }
}
